#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWidgets>

namespace{
QStateMachine g_machine{};
const char *g_host{"10.0.3.188"};
constexpr u_int16_t g_port{8080};
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("Client");
    OnInitDialog();
}

MainWindow::~MainWindow()
{
    delete ui;
    if(m_client)
    {
        m_client->Stop();
        HP_Destroy_TcpClient(m_client);
    }
}

void MainWindow::OnInitDialog()
{
    if(nullptr == m_client)
    {
        auto conn_cb = [this](char*ip,int ip_len,uint16_t port,bool conn){return this->OnConnect(ip,ip_len,port,conn);};
        m_listener.SetConnectCB(conn_cb);
        auto msg_cb = [this](char*data,int data_len){return this->OnMessage(data,data_len);};
        m_listener.SetMessageCB(msg_cb);
        m_client = HP_Create_TcpClient(&m_listener);
    }
    Q_ASSERT(m_client);
    connect(ui->pushButton_send,&QPushButton::clicked,this,[this]{
        if(m_client)
        {
            auto context = ui->plainTextEdit_tx->toPlainText().trimmed();
            m_client->Send((unsigned char*)context.toLocal8Bit().data(),context.length());
        }
    });

    //
    connect(this,&MainWindow::signal_show_msg,this,[this](const QString&msg){
        ui->plainTextEdit_rx->appendPlainText(msg);
    });
    connect(ui->pushButton_rx_clear,&QPushButton::clicked,this,[this]{ui->plainTextEdit_rx->clear();});
    connect(ui->pushButton_tx_clear,&QPushButton::clicked,this,[this]{ui->plainTextEdit_tx->clear();});
    if(auto btn = ui->pushButton_open;btn)
    {
        QState *on = new QState();
        QState *off = new QState();
        on->assignProperty(btn,"text","Open");
        off->assignProperty(btn,"text","Close");
        on->addTransition(btn,&QPushButton::clicked,off);
        off->addTransition(btn,&QPushButton::clicked,on);

        g_machine.addState(on);
        g_machine.addState(off);
        g_machine.setInitialState(on);
        g_machine.start();
        connect(ui->pushButton_open,&QPushButton::clicked,this,[this]{
            auto text = ui->pushButton_open->text().trimmed();
            if("Open" == text)
            {if(m_client)m_client->Start(g_host,g_port,TRUE);}
            else
                if(m_client)m_client->Stop();
        });
    }
}

void MainWindow::OnConnect(char *host, int host_len, uint16_t port, bool conn)
{
    Q_UNUSED(host_len);
    emit signal_show_msg(QString("Server IP:%1,Port:%2 conn:%3")
                         .arg(host)
                         .arg(port)
                         .arg(conn?"Conn":"DisConn"));
}

void MainWindow::OnMessage(char *data, int data_len)
{
    emit signal_show_msg(QString("Recv:%1,len:%2")
                         .arg(QString::fromStdString(std::string(data,data_len)))
                         .arg(data_len));
}

